<?php

namespace App\Http\Controllers;


use App\Helpers\Tools;
use App\Models\Adverti;
use App\Models\PrizeDraw;
use Illuminate\Support\Facades\Redis;

class AnswerController extends ApiController
{
    /**
     * 中奖登记
     * @param int $activities_id 活动id
     * @param int $adverti_id 奖券id
     * @param int $nickname 姓名
     * @param string $mobile 电话
     * @param string $address 地址
     *
     * @author 日隆
     * @return $id
     */
    public function apply()
    {
        // 获取数组
        $data = request()->only('activities_id', 'adverti_id', 'nickname', 'mobile', 'address');

        // 判断消耗是否已满
        $places = $this->places($data['adverti_id']);

        if($places) {
            $prizeDraw = new PrizeDraw();
            $prizeDraw->fill($data);
            $res = $prizeDraw->save();

            if ($res) {
                return Tools::success();
            } else {
                return Tools::error('入库失败');
            }
        } else {
            return Tools::error('本奖品已送完，下次参与还有机会哦！');
        }
    }

    /**
     * 获取单条广告信息
     * @param int $adverti_id 奖券id
     *
     * @author 日隆
     * @return $info
     */
    protected function advertiInfo($id)
    {
        $time = time();
        if ($time - Redis::hget("adverti:info:$id", 'updateTime') > 20) {
            $info = Adverti::find($id);

            Redis::hset("adverti:info:$id", 'updateTime', $time);
            Redis::hset("adverti:info:$id", 'info', serialize($info));
            Redis::hset("adverti:info:$id", 'budget', $info->day_budget);
        } else {
            $info = unserialize(Redis::hget("adverti:info:$id", 'info'));
        }

        return $info;
    }

    /**
     *
     * @param int $adverti_id 奖券id
     *
     * @author 日隆
     * @return $adverti
     */
    protected function places($id)
    {
        // 日后将缓存数据添加进表单和修改提交事件里
        $this->advertiInfo($id);

        // 先添加消耗
        $day = date('Y-m-d');
        $useBudget = Redis::hget("adverti:info:$id", "$day:useBudget");

        $budget = Redis::hget("adverti:info:$id", 'budget');

        if ($useBudget <= $budget) {
            return true;
        } else {
            return false;
        }
    }


}
